﻿using UnityEngine;

namespace JH
{
    /// <summary>
    /// 是否重叠判断
    /// </summary>
    public static class IsOverLappingExtension
    {
        /// <summary>
        ///  判断两个碰撞体是否重叠
        /// </summary>
        ///  <param name="targetCollider">目标碰撞体</param>
        ///   <param name="otherCollider">另一个碰撞体</param>
        ///  <param name="anyway">是否强制执行</param>
        ///  <returns>是否重叠</returns>
        ///  <exception cref="System.NotSupportedException">对于非凸碰撞体，使用此函数可能会导致错误的结果！如果您清楚自己的行为，
        /// 可以将 anyway 参数设置为 true。</exception>
        public static bool IsOverlappingEm(this Collider targetCollider, Collider otherCollider, bool anyway = false)
        {
            if (targetCollider == null || otherCollider == null)
            {
                throw new System.ArgumentNullException(targetCollider == null
                    ? nameof(targetCollider)
                    : nameof(otherCollider), "传入的碰撞体为空");
            }

            if (!anyway && (targetCollider is MeshCollider { convex: false } ||
                            otherCollider is MeshCollider { convex: false }))
            {
                throw new System.NotSupportedException(
                    "对于非凸碰撞体，使用此函数可能会导致错误的结果！如果您清楚自己的行为，可以将 anyway 参数设置为 true。");
            }

            var targetTransform = targetCollider.transform;
            var otherTransform = otherCollider.transform;
            return Physics.ComputePenetration(
                targetCollider, targetTransform.position, targetTransform.rotation,
                otherCollider, otherTransform.position, otherTransform.rotation,
                out _, out _);
        }
    }
}